package com.xy_pro.xymanager.validator;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;

public class WXBizDataCrypt {
    static {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }

    private String appId;
    private String sessionKey;

    public WXBizDataCrypt(String appId, String sessionKey) {
        this.appId = appId;
        this.sessionKey = sessionKey;
    }

    /**
     * 解密微信加密数据
     *
     * @param encryptedData 加密数据
     * @param iv            初始向量
     * @return 解密后的 JSON 字符串
     * @throws Exception 解密失败时抛出异常
     */
    public String decryptData(String encryptedData, String iv) throws Exception {
        byte[] sessionKeyBytes = Base64.decodeBase64(sessionKey);
        byte[] encryptedDataBytes = Base64.decodeBase64(encryptedData);
        byte[] ivBytes = Base64.decodeBase64(iv);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        SecretKeySpec keySpec = new SecretKeySpec(sessionKeyBytes, "AES");
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(ivBytes));

        cipher.init(Cipher.DECRYPT_MODE, keySpec, params);
        byte[] result = cipher.doFinal(encryptedDataBytes);

        return new String(result, StandardCharsets.UTF_8);
    }
}
